package com.gxljc.bear.crawler.util;

import com.google.gson.Gson;
import com.gxljc.commons.core.RedisUtils;
import com.gxljc.commons.redis.dao.Basegxljcedis;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * redis util
 * 
 * @author tanghaitao
 */
public abstract class RedisUtil {

	private static Logger LOG = Logger.getLogger(RedisUtil.class);
	private static final int EXPIRE_DAY = 3600 * 24 * 7;// redis key 有效

	protected static Basegxljcedis redisDao;

	static {
		try {
			redisDao = RedisUtils.getgxljcedisInstance();
		} catch (Exception e) {
			LOG.error("init redisDao error!", e);
			throw new RuntimeException(e);
		}
	}

	public static void lpush (String redisKey, String o) throws Exception{
		if (redisKey.equals("") || o == null) {
			LOG.info(String.format("invalid key: %s", redisKey));
		} else {
				redisDao.lpush(redisKey, o);
		}
	}

	public static String rpop(String redisKey) throws Exception {
		return redisDao.rpop(redisKey);
	}

	public static Long llen(String redisKey) throws Exception {
		return redisDao.llen(redisKey);
	}

	/**
	 * 写入redis
	 *
	 * @param id
	 * @param map
	 */
	public static void cache(String id, String redisKey, Map<String, Object> map) {
		if (id == null || map == null) {
			return;
		}
		String key = String.format("%s:%s", redisKey, id);
		try {
			String value = new Gson().toJson(map);
			redisDao.set(key, value);
			redisDao.expire(key, EXPIRE_DAY);
		} catch (Exception e) {
			LOG.error(String.format("###set %s redis cache error!", redisKey), e);
		}
	}

	public static void cache(String id, String redisKey, String content) {
		if (id == null || content == null) {
			return;
		}
		String key = String.format("%s:%s", redisKey, id);
		try {
			String value = content;
			redisDao.set(key, value);
			redisDao.expire(key, EXPIRE_DAY);
		} catch (Exception e) {
			LOG.error(String.format("###set %s redis cache error!", redisKey), e);
		}
	}

	/**
	 * 删除redis key
	 * 
	 * @param id
	 * @param redisKey
	 */
	public static void delCache(String id, String redisKey) {
		if (id == null) {
			return;
		}
		String key = String.format("%s:%s", redisKey, id);
		try {
			redisDao.del(key);
		} catch (Exception e) {
			LOG.error(String.format("###del %s redis cache error!", redisKey), e);
		}
	}

	/**
	 * 从cache中获取
	 * 
	 * @param id
	 * @return
	 */
	public static String getFromCache(String id, String redisKey) {
		String key = String.format("%s:%s", redisKey, id);
		try {
			String value = redisDao.get(key);
			return value;
		} catch (Exception e) {
			LOG.error(String.format("###get %s redis cache error!", redisKey), e);
		}
		return null;
	}

}